import React, { useState, useEffect, useCallback } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  Card,
  Row,
  Col,
  Statistic,
  Tag,
  message,
  Spin,
  Alert,
  Avatar,
  Timeline,
  Typography,
} from 'antd';
import {
  UserOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined,
  GiftOutlined,
  SearchOutlined,
  RedoOutlined,
  UsergroupAddOutlined,
  CheckSquareOutlined,
  HourglassOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import api, { inviteAPI } from '../utils/api';
import BaseTable from '../shared/table/BaseTable';
import { INVITES_COLUMNS } from '../shared/table/columns';
import { getErrorMessage, getSuccessMessage, ERROR_TYPES, SUCCESS_TYPES } from '../utils/i18n';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Title, Text, Paragraph } = Typography;

const InviteManagement = () => {
  const [inviteRecords, setInviteRecords] = useState([]);
  const [stats, setStats] = useState({
    totalInvites: 0,
    successfulInvites: 0,
    pendingInvites: 0,
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [filters, setFilters] = useState({
    status: 'all',
    dateRange: null,
    search: '',
  });
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [isCouponModalVisible, setIsCouponModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [form] = Form.useForm();

  const fetchStats = useCallback(async () => {
    try {
      const response = await inviteAPI.getInviteStats();
      setStats(response.data.data);
    } catch (error) {
      message.error('无法加载统计数据');
      console.error('Failed to fetch stats:', error);
    }
  }, []);

  const fetchInviteRecords = useCallback(async (page, pageSize, currentFilters) => {
    setLoading(true);
    setError(null);
    try {
      const { status, dateRange, search } = currentFilters;
      const params = {
        page,
        limit: pageSize,
        status: status === 'all' ? undefined : status,
        startDate: dateRange && dateRange[0] ? dateRange[0].toISOString() : undefined,
        endDate: dateRange && dateRange[1] ? dateRange[1].toISOString() : undefined,
        search,
      };
      const response = await inviteAPI.getInviteRecords(params);
      setInviteRecords(response.data.data);
      setPagination({
        current: response.data.pagination.page,
        pageSize: response.data.pagination.limit,
        total: response.data.pagination.total,
      });
    } catch (err) {
      setError('无法加载邀请记录。请稍后重试。');
      message.error('无法加载邀请记录');
      console.error('Failed to fetch records:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchStats();
  }, [fetchStats]);

  useEffect(() => {
    fetchInviteRecords(pagination.current, pagination.pageSize, filters);
  }, [pagination.current, pagination.pageSize, filters, fetchInviteRecords]);

  const handleTableChange = (newPagination) => {
    setPagination(p => ({ ...p, current: newPagination.current, pageSize: newPagination.pageSize }));
  };

  const handleFilterChange = (changedFilters) => {
    setFilters(prev => ({ ...prev, ...changedFilters }));
    setPagination(p => ({ ...p, current: 1 }));
  };

  const resetFilters = () => {
    setFilters({
      status: 'all',
      dateRange: null,
      search: '',
    });
    setPagination(p => ({ ...p, current: 1 }));
  };
  
  const handleManualSearch = () => {
    setPagination(p => ({ ...p, current: 1 }));
    // If pagination is already at 1, the effect won't re-trigger, so we call it manually.
    if (pagination.current === 1) {
      fetchInviteRecords(1, pagination.pageSize, filters);
    }
  };

  const showDetailModal = (record) => {
    setCurrentRecord(record);
    setIsDetailModalVisible(true);
  };

  const showCouponModal = (record) => {
    setCurrentRecord(record);
    form.resetFields();
    setIsCouponModalVisible(true);
  };

  const handleCouponSubmit = async () => {
    try {
      const values = await form.validateFields();
      await inviteAPI.issueCoupon(currentRecord.id, {
        inviterAmount: values.inviterAmount || 0,
        inviteeAmount: values.inviteeAmount || 0,
        bonusAmount: values.bonusAmount || 0,
        notes: values.notes,
      });
      message.success(getSuccessMessage('INVITES', SUCCESS_TYPES.ISSUE_SUCCESS));
      setIsCouponModalVisible(false);
      fetchInviteRecords(pagination.current, pagination.pageSize, filters);
      fetchStats();
    } catch (error) {
      message.error(getErrorMessage('INVITES', ERROR_TYPES.ISSUE_FAILED));
      console.error('Failed to issue coupon:', error);
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'pending':
        return 'orange';
      case 'registered':
        return 'blue';
      case 'completed':
        return 'green';
      default:
        return 'default';
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'pending':
        return '待使用';
      case 'registered':
        return '已注册';
      case 'completed':
        return '已完成';
      default:
        return '未知';
    }
  };

  // 基于统一列配置生成实际渲染列
  const renderColumns = (baseColumns) => [
    {
      ...baseColumns[0], // 邀请人
      dataIndex: 'inviter',
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar src={record.inviter_avatar} icon={<UserOutlined />} size="small" />
          <div style={{ marginLeft: 8, overflow: 'hidden' }}>
            <div style={{ fontWeight: 600, whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>
              {record.inviter_name}
            </div>
            <div style={{ fontSize: '12px', color: '#666', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>
              {record.inviter_email}
            </div>
          </div>
        </div>
      ),
    },
    {
      ...baseColumns[1], // 被邀请人
      dataIndex: 'invitee',
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar src={record.invitee_avatar} icon={<UserOutlined />} size="small" />
          <div style={{ marginLeft: 8, overflow: 'hidden' }}>
            <div style={{ fontWeight: 600, whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>
              {record.invitee_name}
            </div>
            <div style={{ fontSize: '12px', color: '#666', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>
              {record.invitee_email}
            </div>
          </div>
        </div>
      ),
    },
    {
      ...baseColumns[2], // 邀请状态
      dataIndex: 'status',
      render: (status) => (
        <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
      ),
    },
    {
      ...baseColumns[3], // 邀请时间
      dataIndex: 'invite_date',
      render: (text) => dayjs(text).format('MM-DD HH:mm'),
    },
    {
      ...baseColumns[4], // 操作
      render: (_, record) => (
        <div style={{ display: 'flex', gap: '4px', justifyContent: 'flex-end' }}>
          <Button type="link" size="small" onClick={() => showDetailModal(record)}>
            详情
          </Button>
          {record.status === 'completed' && record.coupon_status !== 'issued' && (
            <Button type="link" size="small" onClick={() => showCouponModal(record)}>
              发券
            </Button>
          )}
        </div>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>邀请码管理</Title>
      <Paragraph>管理和跟踪用户邀请，发放奖励。</Paragraph>

      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={8}>
          <Card>
            <Statistic
              title="总邀请数"
              value={stats.totalInvites}
              prefix={<UsergroupAddOutlined />}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="成功邀请"
              value={stats.successfulInvites}
              prefix={<CheckSquareOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="待定邀请"
              value={stats.pendingInvites}
              prefix={<HourglassOutlined />}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: '8px' }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
            <Select
              value={filters.status}
              onChange={(value) => handleFilterChange({ status: value })}
              style={{ width: 120 }}
            >
              <Option value="all">所有状态</Option>
              <Option value="successful">成功</Option>
              <Option value="pending">待定</Option>
              <Option value="expired">已过期</Option>
            </Select>
            <RangePicker
              value={filters.dateRange}
              onChange={(dates) => handleFilterChange({ dateRange: dates })}
            />
            <Input
              placeholder="搜索邀请人/被邀请人"
              value={filters.search}
              onChange={(e) => setFilters(f => ({...f, search: e.target.value}))}
              style={{ width: 200 }}
              onPressEnter={handleManualSearch}
              prefix={<SearchOutlined />}
            />
          </div>
          <div style={{ display: 'flex', gap: '8px' }}>
            <Button onClick={resetFilters}>
              <RedoOutlined /> 重置
            </Button>
            <Button type="primary" onClick={handleManualSearch}>
              <SearchOutlined /> 查询
            </Button>
          </div>
        </div>

        {error && <Alert message={error} type="error" style={{ marginBottom: 16 }} />}

        <Spin spinning={loading}>
          <BaseTable
            columns={INVITES_COLUMNS}
            renderColumns={renderColumns}
            dataSource={inviteRecords}
            rowKey="id"
            pagination={pagination}
            onChange={handleTableChange}
          />
        </Spin>
      </Card>

      {currentRecord && (
        <Modal
          title="邀请详情"
          visible={isDetailModalVisible}
          onCancel={() => setIsDetailModalVisible(false)}
          footer={[
            <Button key="back" onClick={() => setIsDetailModalVisible(false)}>
              关闭
            </Button>,
          ]}
          width={680}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Card title="邀请人信息" size="small">
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Avatar size={64} src={currentRecord.inviter_avatar} icon={<UserOutlined />} />
                  <div style={{ marginLeft: 16 }}>
                    <Title level={5}>{currentRecord.inviter_name}</Title>
                    <Text type="secondary">Email: {currentRecord.inviter_email}</Text>
                  </div>
                </div>
              </Card>
            </Col>
            <Col span={12}>
              <Card title="被邀请人信息" size="small">
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Avatar size={64} src={currentRecord.invitee_avatar} icon={<UserOutlined />} />
                  <div style={{ marginLeft: 16 }}>
                    <Title level={5}>{currentRecord.invitee_name}</Title>
                    <Text type="secondary">Email: {currentRecord.invitee_email}</Text>
                  </div>
                </div>
              </Card>
            </Col>
          </Row>
          <Card title="邀请进度" style={{ marginTop: 16 }}>
            <Timeline>
              <Timeline.Item
                dot={<ClockCircleOutlined style={{ fontSize: '16px' }} />}
                color="blue"
              >
                <p>邀请已发送 - {dayjs(currentRecord.invite_date).format('YYYY-MM-DD HH:mm')}</p>
                <Text type="secondary">邀请码: {currentRecord.invite_code}</Text>
              </Timeline.Item>
              {currentRecord.status === 'completed' && (
                <Timeline.Item
                  dot={<CheckCircleOutlined style={{ fontSize: '16px' }} />}
                  color="green"
                >
                  <p>邀请成功 - {dayjs(currentRecord.registration_date).format('YYYY-MM-DD HH:mm')}</p>
                  <Text type="secondary">被邀请人已完成注册和首次购买。</Text>
                </Timeline.Item>
              )}
              {(currentRecord.status === 'pending' || currentRecord.status === 'registered') && (
                <Timeline.Item
                  dot={<HourglassOutlined style={{ fontSize: '16px' }} />}
                  color="orange"
                >
                  <p>邀请待定</p>
                  <Text type="secondary">被邀请人已注册，等待完成首次购买。</Text>
                </Timeline.Item>
              )}
              {currentRecord.status === 'expired' && (
                <Timeline.Item
                  dot={<CloseCircleOutlined style={{ fontSize: '16px' }} />}
                  color="red"
                >
                  <p>邀请已过期 - {dayjs(currentRecord.expires_at).format('YYYY-MM-DD HH:mm')}</p>
                  <Text type="secondary">邀请未在规定时间内完成。</Text>
                </Timeline.Item>
              )}
            </Timeline>
          </Card>
          <Card title="奖励详情" style={{ marginTop: 16 }}>
            {currentRecord.coupon_status === 'issued' ? (
              <div>
                <Paragraph>
                  <CheckCircleOutlined style={{ color: 'green', marginRight: 8 }} />
                  礼券已于 {dayjs(currentRecord.updated_at).format('YYYY-MM-DD HH:mm')} 发放。
                </Paragraph>
                <Paragraph>
                  邀请人礼券: <Text strong>¥{currentRecord.inviter_coupon_amount}</Text><br />
                   被邀请人礼券: <Text strong>¥{currentRecord.invitee_coupon_amount}</Text><br />
                   奖励礼券: <Text strong>¥{currentRecord.bonus_coupon_amount}</Text>
                </Paragraph>
              </div>
            ) : (
              <Paragraph>
                <GiftOutlined style={{ marginRight: 8 }} />
                {currentRecord.status === 'completed' ? '满足奖励条件，可以发放礼券。' : '尚未满足奖励条件。'}
              </Paragraph>
            )}
          </Card>
        </Modal>
      )}

      {currentRecord && (
        <Modal
          title="发放礼券"
          visible={isCouponModalVisible}
          onCancel={() => setIsCouponModalVisible(false)}
          onOk={handleCouponSubmit}
          confirmLoading={loading}
        >
          <p>
            您正在为邀请人 <Text strong>{currentRecord.inviter_name}</Text> (Email: {currentRecord.inviter_email}) 发放礼券，因为他们成功邀请了 <Text strong>{currentRecord.invitee_name}</Text> (Email: {currentRecord.invitee_email})。
          </p>
          <Form form={form} layout="vertical" name="coupon_form">
            <Form.Item
              name="inviterAmount"
              label="邀请人礼券金额"
              rules={[{ required: true, message: '请输入邀请人礼券金额' }]}
            >
              <Input type="number" prefix="¥" />
            </Form.Item>
            <Form.Item
              name="inviteeAmount"
              label="被邀请人礼券金额"
            >
              <Input type="number" prefix="¥" />
            </Form.Item>
            <Form.Item
               name="bonusAmount"
               label="额外奖励金额"
             >
               <Input type="number" prefix="¥" />
             </Form.Item>
             <Form.Item
                name="notes"
                label="备注"
              >
                <Input.TextArea rows={3} placeholder="请输入发放备注" />
              </Form.Item>
          </Form>
        </Modal>
      )}
    </div>
  );
};

export default InviteManagement;